//
//  YHPOAuthViewController.swift
//  SinaSwift
//
//  Created by Yan on 16/3/8.
//  Copyright © 2016年 baidu. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class YHPOAuthViewController: UIViewController {
    
    // 定义属性webView
    let webView = UIWebView()
    
    // 在页面显示时将view替换为webView
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
    }
    override func viewDidAppear(animated: Bool) {
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = commonColor
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
        setNavgationItems()
        loadOAuthPage()
        
    }
    
    //MARK: 加载webview界面
    private func loadOAuthPage() {
//        let urlString = "https://api.weibo.com/oauth2/authorize"
// + "?client_id=\(client_id)"  + "&redirect_uri=\(redirect_uri)"
        let urlString = URL + "?client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

    //MARK: 设置items
    func setNavgationItems() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "defaultAccount")
        //        navigationController?.toolbar.tintColor = commonColor
        navigationController?.navigationBar.tintColor = commonColor
    }
    
    @objc private func defaultAccount () {
    let jsString = "document.getElementById('userId').value = '550872569@qq.com', document.getElementById('passwd').value = 'yhp550872569@YHP'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    @objc  private func close() {
        print("返回")
        // 让modal的控制器消失
        dismissViewControllerAnimated(true, completion: nil)
    }

    
   }

//MARK: UIWebViewDelegateMethod
extension YHPOAuthViewController : UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // print(request.URL)
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
       
        if urlString.containsString("code") {
            // 获取coder
            let query = request.URL?.query
            // print(query)
            /*
            Optional(http://www.baidu.com/?code=1bfcd42be4faa478c580d2e76a900b33)
            Optional(https://m.baidu.com/?code=1bfcd42be4faa478c580d2e76a900b33&from=844b&vit=fps)
            */
            let codeStr = "code="
            // 获取code
            let code = (query! as NSString).substringFromIndex(codeStr.characters.count)
            //            print(code)
//            loadAccountToken(code)
            YHPUserAccount.shareAccount.loadAccountToken(code, finish: { (isSuccess) -> () in
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus("网络加载失败")
                    return
                }
                self.close()
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: "OAuth")
            })
            return false
        }
        
        return true
    }

}

